package controller

import (
	"ginEssential/common"
	"ginEssential/dto"
	"ginEssential/model"
	"ginEssential/response"
	"ginEssential/util"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
)

func Register(c *gin.Context) {
	db := common.GetDB()
	//var requestMap=make(map[string]string)  Map获得参数
	//json.NewDecoder(c.Request.Body).Decode(requestMap)

	var user model.User //使用gin来获得
	//json.NewDecoder(c.Request.Body).Decode(&user)
	c.BindJSON(&user)
	//获取参数
	name := user.Name
	telephone := user.Telephone
	password := user.Password

	//数据的验证
	if len(telephone) != 11 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位数字尼玛的手机号都属不来给爷爬")
		//c.IndentedJSON(http.StatusUnprocessableEntity, gin.H{
		//	"code": 422, "msg": "手机号必须为11位数字尼玛的手机号都属不来给爷爬",
		//})
		return
	}
	if len(password) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码必须大于等于6位")
		//c.IndentedJSON(http.StatusUnprocessableEntity, gin.H{
		//	"code": 422, "msg": "密码必须大于等于6位",
		//})
		return
	}
	if len(name) == 0 {
		name = util.RandomString(10)
	}
	log.Println(name, password, telephone)
	//判断手机号是否存在

	if isExistTelephone(db, telephone) {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "该手机已经被注册")
		//c.IndentedJSON(http.StatusUnprocessableEntity, gin.H{
		//	"code": 422, "msg": "该手机已经被注册",
		//})
		return
	}
	//创建用户
	hashedpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) //加密密码
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 422, nil, "加密错误")
		//c.IndentedJSON(http.StatusInternalServerError,gin.H{
		//	"code":500,
		//	"msg":"加密错误",
		//})
		return
	}
	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  string(hashedpassword),
	}
	db.Create(&newUser)
	//正确 发放token
	token, err := common.ReleaseToken(newUser)
	if err != nil {
		c.IndentedJSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "系统生成tokens失败",
		})
		log.Printf("token generate error: %v\n", err)
		return
	}
	//返回结果
	response.Success(c, gin.H{"token":token}, "注册成功")
	//c.IndentedJSON(http.StatusOK, gin.H{
	//	"msg": "注册成功",
	//})

}

func Login(c *gin.Context) {
	db := common.GetDB()
	//获取参数
	telephone := c.PostForm("telephone")
	password := c.PostForm("password")
	//数据验证

	if len(telephone) != 11 {
		c.IndentedJSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422, "msg": "手机号必须为11位数字尼玛的手机号都属不来给爷爬",
		})
		return
	}
	if len(password) < 6 {
		c.IndentedJSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422, "msg": "密码必须大于等于6位",
		})
		return
	}
	//判断手机号是否正确
	var user model.User
	db.Where("telephone=?", telephone).First(&user)
	if user.ID == 0 {
		c.IndentedJSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "用户不存在",
		})
		return
	}
	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		c.IndentedJSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	//正确 发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		c.IndentedJSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "系统生成tokens失败",
		})
		log.Printf("token generate error: %v\n", err)
		return
	}
	//返回结果
	c.IndentedJSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{"token": token},
		"msg":  "登陆成功",
	})
}

//登录或者登录过，会发放过一个token，token经过中间件验证之后到达这一步，显示个人信息
func Info(c *gin.Context) {
	user, _ := c.Get("user")
	c.IndentedJSON(http.StatusOK, gin.H{
		"code": 200,
		"user": dto.ToUserDto(user.(model.User)), //转为UserDTO，由于GET得到的是 interface{} 所以需要类型断言
	})
}

func isExistTelephone(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone = ? ", telephone).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}
